import { MouseEventHandler, useContext } from "react";
import { ReducerContext } from "../reducer/ReducerProvider";

export interface DragProps {
  onMouseDown: MouseEventHandler;
  x: string;
  y: string;
}

/**
 *
 * @param WrappedComponent 需要加载拖拽事件的组件
 * @param defaultPosition 在svg初始位置，左上角为{x:"0",y:"0"}
 */
export default function withDragEvent(
  WrappedComponent: (props: DragProps) => JSX.Element,
  defaultPosition: {
    x: string;
    y: string;
    index: number;
  }
) {
  return function () {
    const { dispatch } = useContext(ReducerContext);
    const { x, y, index } = defaultPosition;
    let startX = 0;
    let startY = 0;
    let offsetX = 0;
    let offsetY = 0;
    let isMouseDown = false;

    function mouseDown(e: React.MouseEvent<EventTarget>) {
      isMouseDown = true;
      startX = e.clientX;
      startY = e.clientY;
      offsetX = startX - parseInt(x);
      offsetY = startY - parseInt(y);
      document.body.onmousemove = mouseMove;
      document.body.onmouseup = mouseUp;
    }
    function mouseMove(e: MouseEvent) {
      if (isMouseDown) {
        const distanceX = e.clientX - startX;
        const distanceY = e.clientY - startY;
        dispatch({
          index,
          x: (startX - offsetX + distanceX).toString(),
          y: (startY - offsetY + distanceY).toString(),
          type: "unit",
        });
      }
    }
    function mouseUp() {
      isMouseDown = false;
    }
    return <WrappedComponent onMouseDown={(e) => mouseDown(e)} x={x} y={y} />;
  };
}
